package sipus.action.maintenance;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.hibernate.Session;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.util.GenericAutowireComposer;
import org.zkoss.zul.Borderlayout;
import org.zkoss.zul.Caption;
import org.zkoss.zul.Center;
import org.zkoss.zul.Checkbox;
import org.zkoss.zul.Detail;
import org.zkoss.zul.Grid;
import org.zkoss.zul.Groupbox;
import org.zkoss.zul.Hbox;
import org.zkoss.zul.Label;
import org.zkoss.zul.ListModel;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Row;
import org.zkoss.zul.RowRenderer;
import org.zkoss.zul.Rows;
import org.zkoss.zul.SimpleListModel;
import org.zkoss.zul.South;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Toolbar;
import org.zkoss.zul.Toolbarbutton;
import org.zkoss.zul.Tree;
import org.zkoss.zul.Treecell;
import org.zkoss.zul.Treechildren;
import org.zkoss.zul.Treecol;
import org.zkoss.zul.Treecols;
import org.zkoss.zul.Treeitem;
import org.zkoss.zul.Treerow;
import org.zkoss.zul.Window;

import sipus.action.master.helper.RevisiHelper;
import sipus.common.Common;
import sipus.common.CommonPrivilages;
import sipus.database.dao.DaoFactory;
import sipus.database.dao.TbmroleDao;
import sipus.database.hibernate.HibernateUtil;
import sipus.database.model.Menu;
import sipus.database.model.RolePrivilage;
import sipus.database.model.Tbmrole;
import sipus.database.model.Tbmuser;


public class TbmroleAction extends GenericAutowireComposer {

	/**
	 * 
	 */
	private static final long serialVersionUID = -5779730267402400328L;
	private Window addWindow;
	private Window addMenu;
	private Grid grid;

	private Textbox searchnama;
	private Textbox nama;
	private Textbox kode;
	private Textbox dashboard;

	private Tbmrole tbmrole;
	private Toolbarbutton add;

	private boolean edit;
	private boolean delete;
	private Textbox dashboard2;
	private Textbox dashboard3;

	@Override
	public void doAfterCompose(Component comp) throws Exception {
		// TODO Auto-generated method stub
		super.doAfterCompose(comp);

		Tbmuser tbmuser = Common.getCurrentUser();

		if (session.getAttribute("usersTemp") == null
				|| !CommonPrivilages.checkPrevilages(CommonPrivilages.READ)

				|| tbmuser.getRoot() == null || !tbmuser.getRoot()

		) {
			session.removeAttribute("usersTemp");
			execution.sendRedirect("/logoff");
			return;
		}

		edit = CommonPrivilages.checkPrevilages(CommonPrivilages.UPDATE);
		delete = CommonPrivilages.checkPrevilages(CommonPrivilages.DELETE);

		add.setVisible(CommonPrivilages
				.checkPrevilages(CommonPrivilages.CREATE));
		add.setTooltiptext("Tambah");

		CommonPrivilages.checkPrevilages(CommonPrivilages.UPDATE);
		CommonPrivilages.checkPrevilages(CommonPrivilages.DELETE);
		onSearchDefault(null);
	}

	class TbmroleRenderer implements RowRenderer {

		class MenuSelecter {

			private Map<Integer, Object[]> checkboxs = new HashMap<Integer, Object[]>();
			private Window window;
			private Tbmrole job;
			private Groupbox groupbox;

			public synchronized MenuSelecter createInstance(Tbmrole job,
					Groupbox groupbox) throws Exception {

				// System.out.println("job menu = " + job.getMenus().size());
				// this.window=addMenu;
				System.out.println("menuselecternyaaaaaaaaaaa" + menuSelecter);
				MenuSelecter menuSelecter = new MenuSelecter();
				menuSelecter.window = addMenu;
				System.out.println("menuselecternyaaaaaaaaaaa"
						+ menuSelecter.window);
				menuSelecter.job = job;
				menuSelecter.groupbox = groupbox;
				menuSelecter.init();
				menuSelecter.window.setVisible(true);
				menuSelecter.window.onModal();
				return menuSelecter;
			}

			private MenuSelecter() {

			}

			private synchronized Boolean hasChild(Integer root, List<Menu> menus) {
				for (Menu menu : menus) {
					if (menu.getRoot().equals(root)) {
						return true;
					}
				}
				return false;
			}

			private void createTreerow(Treeitem treeitem, final Menu menu) {
				Treerow treerow = new Treerow();
				new Treecell(menu.getLabel()).setParent(treerow);

				Treecell treecell = new Treecell();
				final Checkbox checkbox = new Checkbox();
				if (job != null && job.getMenus() != null) {
					for (Menu myMenu : job.getMenus()) {
						if (menu.getId().equals(myMenu.getId())) {
							checkbox.setChecked(true);
							break;
						}
					}
				}
				checkboxs.put(new Double(1000000.0 * Math.random()).intValue(),
						new Object[] { checkbox, menu });
				checkbox.setParent(treecell);
				treecell.setParent(treerow);
				treerow.setParent(treeitem);
			}

			private void createRootSubMenu(Integer root, List<Menu> menus,
					Component componen) {
				Treechildren tc1 = new Treechildren();
				for (final Menu menu : menus) {
					if (menu.getRoot().equals(root)) {
						Boolean ada = hasChild(menu.getChild(), menus);
						if (ada) {
							Treeitem treeitem = new Treeitem();
							treeitem.setValue(menu.getUrl());
							createTreerow(treeitem, menu);
							treeitem.setParent(tc1);
							createRootSubMenu(menu.getChild(), menus, treeitem);
						} else {
							Treeitem treeitem = new Treeitem();
							treeitem.setValue(menu.getUrl());
							createTreerow(treeitem, menu);
							treeitem.setParent(tc1);
						}
					}
				}

				tc1.setParent(componen);
			}

			public void createTreeMenu(Tree tree, final List<Menu> menus) {

				Treecols treecols = new Treecols();
				Treecol treecol = new Treecol("Tree Menu");
				treecol.setWidth("95%");
				treecol.setParent(treecols);
				treecol = new Treecol("");
				treecol.setWidth("5%");
				treecol.setParent(treecols);
				treecols.setParent(tree);

				Treechildren tc1 = new Treechildren();
				for (final Menu menu : menus) {
					if (menu.getRoot().equals(0)) {
						Treeitem treeitem = new Treeitem();
						treeitem.setValue(menu.getUrl());
						createTreerow(treeitem, menu);
						treeitem.setParent(tc1);
						createRootSubMenu(menu.getChild(), menus, treeitem);
					}
				}
				tc1.setParent(tree);
			}

			private void save() throws Exception {
				job.setMenus(new HashSet<Menu>());

				for (Object[] objs : this.checkboxs.values()) {
					Checkbox combobox = (Checkbox) objs[0];
					Menu myMenu = (Menu) objs[1];
					Boolean check = combobox.isChecked();
					System.out.println("menu = " + myMenu.getLabel()
							+ ", check = " + check);
					if (check) {

						job.getMenus().add(myMenu);
					}

				}
				Session session = HibernateUtil.currentSession();
				try {

					session.update(session.merge(job));

					List<?> list = groupbox.getChildren();
					((Component) list.get(0)).detach();
					((Component) list.get(0)).detach();

					final Tree mytree = createTree(job, groupbox);
					mytree.setVisible(true);
					tbmroleActionHelper.createTreeMenu(groupbox, mytree, job);

				} catch (Exception e) {
					e.printStackTrace();

					Messagebox.show("Data ini tidak bisa ditambahkan ..");
				}

				window.setVisible(false);
			}

			@SuppressWarnings("unchecked")
			private void init() {

				Common.clear(window);
				Borderlayout borderlayout = new Borderlayout();
				Center center = new Center();
				center.setFlex(true);

				Session session = HibernateUtil.currentSession();

				List<Menu> menus = session.createCriteria(Menu.class).list();
				final Tree tree = new Tree();
				createTreeMenu(tree, menus);
				tree.setParent(center);

				Caption caption = new Caption();
				Toolbarbutton button = new Toolbarbutton(" X ");
				button.addEventListener("onClick", new EventListener() {
					@Override
					public void onEvent(Event event) throws Exception {
						window.setVisible(false);
					}

				});
				button.setParent(caption);

				center.setParent(borderlayout);

				South south = new South();
				south.setFlex(true);
				south.setParent(borderlayout);

				Toolbar toolbar = new Toolbar();
				toolbar.setHeight("30px");
				button = new Toolbarbutton("Batal", "/img/cancel.gif");
				button.setTooltiptext("Tutup");
				button.addEventListener("onClick", new EventListener() {
					@Override
					public void onEvent(Event event) throws Exception {
						window.setVisible(false);
					}

				});
				button.setParent(toolbar);

				button = new Toolbarbutton("Simpan", "/img/save.gif");
				button.setTooltiptext("Simpan");
				button.addEventListener("onClick", new EventListener() {
					@Override
					public void onEvent(Event event) throws Exception {
						save();
					}

				});
				button.setParent(toolbar);

				toolbar.setParent(south);

				borderlayout.setParent(window);
				// caption.setParent(window);
			}

		}

		class TbmroleActionHelper {

			private synchronized Boolean hasChild(Integer root, Set<Menu> menus) {
				for (Menu menu : menus) {
					if (menu.getRoot().equals(root)) {
						return true;
					}
				}
				return false;
			}

			private synchronized void createTreerow(final Tree tree,
					final Groupbox groupbox, Treeitem treeitem,
					final Menu menu, final Tbmrole job) {
				Treerow treerow = new Treerow();
				Toolbarbutton button = new Toolbarbutton();
				new Treecell(menu.getLabel()).setParent(treerow);
				final Checkbox all = new Checkbox();
				final Checkbox update = new Checkbox();
				final Checkbox read = new Checkbox();
				final Checkbox delete = new Checkbox();
				final Checkbox create = new Checkbox();

				// TODO: buatkan ckeckbox disini, langsung pake eventListener,
				// jika di
				// check langsung transaksi dgn database, insert/update model
				// RolePrivilage.java
				// new Treecell("Read").setParent(treerow);

				Treecell treecell = new Treecell();
				Session session = HibernateUtil.currentSession();
				RolePrivilage roles = (RolePrivilage) session
						.createCriteria(RolePrivilage.class)
						.add(Restrictions.eq("role", job))
						.add(Restrictions.eq("menu", menu)).setMaxResults(1)
						.uniqueResult();

				read.addEventListener("onCheck", new EventListener() {
					@Override
					public void onEvent(Event event) throws Exception {
						// TODO Auto-generated method stub
						Session session = HibernateUtil.currentSession();
						RolePrivilage rolePrivilage = (RolePrivilage) session
								.createCriteria(RolePrivilage.class)
								.add(Restrictions.eq("role", job))
								.add(Restrictions.eq("menu", menu))
								.setMaxResults(1).uniqueResult();

						if (rolePrivilage == null) {
							rolePrivilage = new RolePrivilage();
							rolePrivilage.setCreate(0);
							rolePrivilage.setDelete(0);
							rolePrivilage.setUpdate(0);
						} else {
							rolePrivilage.setRole(job);
							rolePrivilage.setMenu(menu);
							if (read.isChecked()) {
								rolePrivilage.setRead(1);
								if (rolePrivilage.getRead().equals(1)
										&& rolePrivilage.getCreate().equals(1)
										&& rolePrivilage.getUpdate().equals(1)
										&& rolePrivilage.getDelete().equals(1)) {
									all.setChecked(true);
								}
							} else {
								rolePrivilage.setRead(0);
								all.setChecked(false);
							}
							// rolePrivilage.setRead(read.isChecked() ? 1 : 0);

							session.saveOrUpdate(rolePrivilage);

						}
					}

				});

				read.setParent(treecell);
				treecell.setParent(treerow);

				// new Treecell("Update").setParent(treerow);
				Treecell treecell2 = new Treecell();

				update.addEventListener("onCheck", new EventListener() {

					@Override
					public void onEvent(Event event) throws Exception {
						// TODO Auto-generated method stub
						Session session = HibernateUtil.currentSession();
						RolePrivilage rolePrivilage = (RolePrivilage) session
								.createCriteria(RolePrivilage.class)
								.add(Restrictions.eq("role", job))
								.add(Restrictions.eq("menu", menu))
								.setMaxResults(1).uniqueResult();

						if (rolePrivilage == null) {
							rolePrivilage = new RolePrivilage();
							rolePrivilage.setRead(0);
							rolePrivilage.setDelete(0);
							rolePrivilage.setCreate(0);
						} else {
							rolePrivilage.setRole(job);
							rolePrivilage.setMenu(menu);
							if (update.isChecked()) {
								rolePrivilage.setUpdate(1);
								if (rolePrivilage.getRead().equals(1)
										&& rolePrivilage.getCreate().equals(1)
										&& rolePrivilage.getUpdate().equals(1)
										&& rolePrivilage.getDelete().equals(1)) {
									all.setChecked(true);
								}

							} else {
								rolePrivilage.setUpdate(0);
								all.setChecked(false);
							}
							// rolePrivilage.setUpdate(update.isChecked() ? 1 :
							// 0);

							session.saveOrUpdate(rolePrivilage);

						}
					}
				});

				update.setParent(treecell2);
				treecell2.setParent(treerow);

				// new Treecell("Create").setParent(treerow);
				Treecell treecell3 = new Treecell();

				create.addEventListener("onCheck", new EventListener() {

					@Override
					public void onEvent(Event event) throws Exception {
						// TODO Auto-generated method stub
						Session session = HibernateUtil.currentSession();
						RolePrivilage rolePrivilage = (RolePrivilage) session
								.createCriteria(RolePrivilage.class)
								.add(Restrictions.eq("role", job))
								.add(Restrictions.eq("menu", menu))
								.setMaxResults(1).uniqueResult();

						if (rolePrivilage == null) {
							rolePrivilage = new RolePrivilage();
							rolePrivilage.setRead(0);
							rolePrivilage.setDelete(0);
							rolePrivilage.setUpdate(0);
						} else {
							rolePrivilage.setRole(job);
							rolePrivilage.setMenu(menu);
							// rolePrivilage.setCreate(create.isChecked()?1:0);

							if (create.isChecked()) {
								rolePrivilage.setCreate(1);
								if (rolePrivilage.getRead().equals(1)
										&& rolePrivilage.getCreate().equals(1)
										&& rolePrivilage.getUpdate().equals(1)
										&& rolePrivilage.getDelete().equals(1)) {
									all.setChecked(true);
								}

							} else {
								rolePrivilage.setCreate(0);
								all.setChecked(false);
							}

							session.saveOrUpdate(rolePrivilage);

						}
					}
				});
				create.setParent(treecell3);
				treecell3.setParent(treerow);

				// new Treecell("Delete").setParent(treerow);
				Treecell treecell4 = new Treecell();

				delete.addEventListener("onCheck", new EventListener() {

					@Override
					public void onEvent(Event event) throws Exception {
						// TODO Auto-generated method stub
						Session session = HibernateUtil.currentSession();
						RolePrivilage rolePrivilage = (RolePrivilage) session
								.createCriteria(RolePrivilage.class)
								.add(Restrictions.eq("role", job))
								.add(Restrictions.eq("menu", menu))
								.setMaxResults(1).uniqueResult();

						if (rolePrivilage == null) {
							rolePrivilage = new RolePrivilage();
							rolePrivilage.setRead(0);
							rolePrivilage.setCreate(0);
							rolePrivilage.setUpdate(0);
						} else {
							rolePrivilage.setRole(job);
							rolePrivilage.setMenu(menu);
							// rolePrivilage.setDelete(delete.isChecked()?1:0);
							if (delete.isChecked()) {
								rolePrivilage.setDelete(1);
								if (rolePrivilage.getRead().equals(1)
										&& rolePrivilage.getCreate().equals(1)
										&& rolePrivilage.getUpdate().equals(1)
										&& rolePrivilage.getDelete().equals(1)) {
									all.setChecked(true);
								}

							} else {
								rolePrivilage.setDelete(0);
								all.setChecked(false);
							}

							session.saveOrUpdate(rolePrivilage);

						}
					}
				});

				delete.setParent(treecell4);
				treecell4.setParent(treerow);
				// TODO: end
				Treecell treecell6 = new Treecell();

				all.addEventListener("onCheck", new EventListener() {

					@Override
					public void onEvent(Event event) throws Exception {
						// TODO Auto-generated method stub
						Session session = HibernateUtil.currentSession();
						RolePrivilage rolePrivilage = (RolePrivilage) session
								.createCriteria(RolePrivilage.class)
								.add(Restrictions.eq("role", job))
								.add(Restrictions.eq("menu", menu))
								.setMaxResults(1).uniqueResult();

						if (rolePrivilage == null) {
							rolePrivilage = new RolePrivilage();
							rolePrivilage.setCreate(1);
							rolePrivilage.setRead(1);
							rolePrivilage.setUpdate(1);
							rolePrivilage.setDelete(1);
						} else {
							rolePrivilage.setRole(job);
							rolePrivilage.setMenu(menu);

							rolePrivilage.setRead(all.isChecked() ? 1 : 0);
							read.setChecked(true);
							rolePrivilage.setCreate(all.isChecked() ? 1 : 0);
							create.setChecked(true);
							rolePrivilage.setUpdate(all.isChecked() ? 1 : 0);
							update.setChecked(true);
							rolePrivilage.setDelete(all.isChecked() ? 1 : 0);

							if (all.isChecked()) {
								rolePrivilage.setRead(1);
								read.setChecked(true);
								rolePrivilage.setCreate(1);
								create.setChecked(true);
								rolePrivilage.setUpdate(1);
								update.setChecked(true);
								rolePrivilage.setDelete(1);
								delete.setChecked(true);
							} else {
								read.setChecked(false);
								rolePrivilage.setRead(0);
								create.setChecked(false);
								rolePrivilage.setCreate(0);
								update.setChecked(false);
								rolePrivilage.setUpdate(0);
								delete.setChecked(false);
								rolePrivilage.setDelete(0);
							}

							session.saveOrUpdate(rolePrivilage);

						}
					}
				});
				all.setParent(treecell6);
				treecell6.setParent(treerow);

				// Edited by Fauzi
				// if(roles.getRead().equals(1)
				// && roles.getCreate().equals(1)
				// && roles.getUpdate().equals(1)
				// && roles.getDelete().equals(1)){
				// all.setChecked(true);
				// }

				if (roles != null && roles.getRead().equals(1)
						&& roles.getCreate().equals(1)
						&& roles.getUpdate().equals(1)
						&& roles.getDelete().equals(1)) {
					all.setChecked(true);
				} else {
					all.setChecked(false);
				}

				if (roles != null && roles.getRead().equals(1)) {
					read.setChecked(true);
				} else {
					read.setChecked(false);
				}
				if (roles != null && roles.getUpdate().equals(1)) {
					update.setChecked(true);
				} else {
					update.setChecked(false);
				}
				if (roles != null && roles.getCreate().equals(1)) {
					create.setChecked(true);
				} else {
					create.setChecked(false);
				}
				if (roles != null && roles.getDelete().equals(1)) {
					delete.setChecked(true);
				} else {
					delete.setChecked(false);
				}

				Treecell treecell5 = new Treecell();
				Toolbar toolbar = new Toolbar();
				toolbar.setHeight("30px");
				button = new Toolbarbutton("", "/img/delete.gif");
				button.setTooltiptext("Hapus Data");
				button.addEventListener("onClick", new EventListener() {
					@Override
					public void onEvent(Event event) throws Exception {
						// TODO Auto-generated method stub
						Messagebox.show(
								"Apakah anda ingin menghapus menu ini ?",
								"Question", Messagebox.OK | Messagebox.CANCEL,
								Messagebox.QUESTION, new EventListener() {

									@Override
									public void onEvent(Event event)
											throws Exception {
										int i = new Integer(event.getData()
												.toString());
										if (i == Messagebox.OK) {
											job.getMenus().remove(menu);
											Session session = HibernateUtil
													.currentSession();
											try {

												session.update(session
														.merge(job));

												List<?> list = groupbox
														.getChildren();
												((Component) list.get(0))
														.detach();
												((Component) list.get(0))
														.detach();

												final Tree mytree = createTree(
														job, groupbox);
												mytree.setVisible(true);
												createTreeMenu(groupbox,
														mytree, job);

											} catch (Exception e) {
												e.printStackTrace();

												Messagebox
														.show("Data ini tidak bisa dirubah ..");
											}

										}

									}
								});

					}

				});
				button.setParent(toolbar);
				toolbar.setParent(treecell5);
				treecell5.setParent(treerow);
				treerow.setParent(treeitem);

				// Edited by Fauzi

				if (roles == null) {
					roles = new RolePrivilage();
					roles.setCreate(0);
					roles.setDelete(0);
					roles.setRead(0);
					roles.setUpdate(0);
					roles.setMenu(menu);
					roles.setRole(job);
				}

				session.saveOrUpdate(roles);

			}

			private synchronized void createRootSubMenu(Tree tree,
					final Groupbox groupbox, Integer root, Set<Menu> menus,
					Component componen, Tbmrole job, Set<Integer> check) {
				Treechildren tc1 = new Treechildren();
				for (final Menu menu : menus) {
					if (menu.getRoot().equals(root)
							&& !check.contains(menu.getId())) {
						check.add(menu.getId());
						Boolean ada = hasChild(menu.getChild(), menus);
						if (ada) {
							Treeitem treeitem = new Treeitem();
							treeitem.setValue(menu.getUrl());
							createTreerow(tree, groupbox, treeitem, menu, job);
							treeitem.setParent(tc1);
							createRootSubMenu(tree, groupbox, menu.getChild(),
									menus, treeitem, job, check);
						} else {
							Treeitem treeitem = new Treeitem();
							treeitem.setValue(menu.getUrl());
							createTreerow(tree, groupbox, treeitem, menu, job);
							treeitem.setParent(tc1);
						}
					}
				}

				tc1.setParent(componen);
			}

			public synchronized void createTreeMenu(final Groupbox groupbox,
					Tree tree, Tbmrole job) {
				Set<Integer> check = new HashSet<Integer>();
				Treecols treecols = new Treecols();
				Treecol treecol = new Treecol("");
				treecol.setWidth("75%");
				treecol.setParent(treecols);
				treecol = new Treecol("Read");
				treecol.setWidth("5%");
				treecol.setParent(treecols);
				treecol = new Treecol("Update");
				treecol.setWidth("5%");
				treecol.setParent(treecols);
				treecol = new Treecol("Create");
				treecol.setWidth("5%");
				treecol.setParent(treecols);
				treecol = new Treecol("Delete");
				treecol.setWidth("5%");
				treecol.setParent(treecols);
				treecol = new Treecol("Check All");
				treecol.setWidth("5%");
				treecol.setParent(treecols);
				treecol = new Treecol("");
				treecol.setWidth("5%");
				treecol.setParent(treecols);
				treecols.setParent(tree);

				final Set<Menu> menus = job.getMenus();
				Treechildren tc1 = new Treechildren();
				for (final Menu menu : menus) {
					if (menu.getRoot().equals(0)
							&& !check.contains(menu.getId())) {
						check.add(menu.getId());
						System.out.println("menu = " + menu.getLabel());
						Treeitem treeitem = new Treeitem();
						treeitem.setValue(menu.getUrl());
						createTreerow(tree, groupbox, treeitem, menu, job);
						treeitem.setParent(tc1);
						createRootSubMenu(tree, groupbox, menu.getChild(),
								menus, treeitem, job, check);
					}
				}
				tc1.setParent(tree);
			}

		}

		private MenuSelecter menuSelecter = new MenuSelecter();
		private TbmroleActionHelper tbmroleActionHelper = new TbmroleActionHelper();

		public synchronized Tree createTree(final Tbmrole job,
				final Groupbox groupbox) {
			final Tree tree = new Tree();

			tree.setId("tree_" + (Math.random() * 10000000.0));
			Toolbar toolbar = new Toolbar();
			toolbar.setHeight("30px");

			Toolbarbutton button = new Toolbarbutton("Rubah Struktur Menu",
					"/img/new.gif");
			button.addEventListener("onClick", new EventListener() {
				@Override
				public void onEvent(Event event) throws Exception {
					menuSelecter.createInstance(job, groupbox);

				}

			});

			button.setParent(toolbar);

			toolbar.setParent(groupbox);
			tree.setParent(groupbox);
			tree.setVisible(true);
			return tree;
		}

		@Override
		public void render(final Row arg0, Object arg1) throws Exception {
			final Tbmrole job = (Tbmrole) arg1;

			final Detail detail = new Detail();
			detail.setParent(arg0);

			detail.addEventListener("onOpen", new EventListener() {
				public void onEvent(Event event) throws Exception {
					Common.clear(detail);
					if (detail.isOpen()) {
						Common.clear(detail);
						Groupbox groupbox = new Groupbox();
						groupbox.setMold("3d");
						groupbox.setWidth("100%");

						Tbmrole myjob = (Tbmrole) HibernateUtil
								.currentSession().load(Tbmrole.class,
										job.getRoleId());

						final Tree tree = createTree(myjob, groupbox);
						tbmroleActionHelper.createTreeMenu(groupbox, tree,
								myjob);
						groupbox.setParent(detail);
					}
				}
			});

			new Label(job.getRoleId()).setParent(arg0);
			RevisiHelper.createNewRevisi(Tbmrole.class, job, job.getRoleName())
					.setParent(arg0);
			new Label(job.getDashboard() == null ? "" : job.getDashboard())
					.setParent(arg0);
			new Label(job.getDashboard2() == null ? "" : job.getDashboard2())
					.setParent(arg0);
			new Label(job.getDashboard3() == null ? "" : job.getDashboard3())
					.setParent(arg0);

			Hbox toolbar = new Hbox();
			toolbar.setHeight("30px");
			Toolbarbutton button = new Toolbarbutton("", "/img/edit.gif");
			button.setTooltiptext("Rubah Data");
			button.setVisible(edit);
			button.addEventListener("onClick", new EventListener() {
				@Override
				public void onEvent(Event event) throws Exception {
					init(job);
					addWindow.setVisible(true);
					addWindow.onModal();

				}

			});
			button.setParent(toolbar);

			button = new Toolbarbutton("", "/img/delete.gif");
			button.setTooltiptext("Hapus Data");
			button.setVisible(delete);
			button.addEventListener("onClick", new EventListener() {
				@Override
				public void onEvent(Event event) throws Exception {
					// TODO Auto-generated method stub

					Messagebox.show("Apakah yakin ingin menghapus data ini ?",
							"Question", Messagebox.OK | Messagebox.CANCEL,
							Messagebox.QUESTION, new EventListener() {

								@Override
								public void onEvent(Event event)
										throws Exception {
									int i = new Integer(event.getData()
											.toString());
									if (i == Messagebox.OK) {
										try {
											TbmroleDao tbmroleDao = DaoFactory
													.getInstance()
													.getTbmroleDao();
											// tbmroleDao.beginTransaction();
											tbmroleDao.delete(tbmroleDao
													.merge(tbmrole));
											// tbmroleDao.commitTransaction();
											onSearchDefault(event);
										} catch (Exception e) {
											e.printStackTrace();
											Messagebox
													.show("Data ini tidak dapat dihapus .., karena berelasi dengan data lainnya, error-nya adalah sbagai berikut:"
															+ e.getMessage());
										}

									}

								}
							});

				}

			});
			button.setParent(toolbar);
			toolbar.setParent(arg0);
		}

	}

	public void onAdd(Event event) throws Exception {
		init(new Tbmrole());
		addWindow.setVisible(true);
		addWindow.onModal();
	}

	private void init(Tbmrole tbmrole) {
		this.tbmrole = tbmrole;
		addWindow.setTitle("Pendataan Tbmrole");
		Common.clear(addWindow);
		Borderlayout borderlayout = new Borderlayout();
		Center center = new Center();
		center.setParent(borderlayout);
		center.setFlex(true);
		Grid grid = new Grid();
		grid.setParent(center);
		grid.setWidth("100%");
		grid.setHeight("100%");
		// grid.setOddRowSclass("non-odd");

		Rows rows = new Rows();
		rows.setParent(grid);

		Row row = new Row();
		row.setStyle("border:0px;background: transparent;");
		row.setParent(rows);
		row.appendChild(new Label("Kode Role"));
		row.appendChild(kode = new Textbox(tbmrole.getRoleId() == null ? ""
				: tbmrole.getRoleId()));
		

		row = new Row();
		row.setStyle("border:0px;background: transparent;");
		row.setParent(rows);
		row.appendChild(new Label("Nama Role"));
		row.appendChild(nama = new Textbox(tbmrole.getRoleName() == null ? ""
				: tbmrole.getRoleName()));
		nama.setCols(40);

		row = new Row();
		row.setStyle("border:0px;background: transparent;");
		row.setParent(rows);
		row.appendChild(new Label("Dashboard 1"));
		row.appendChild(dashboard = new Textbox(
				tbmrole.getDashboard() == null ? "" : tbmrole.getDashboard()));
		dashboard.setCols(40);

		row = new Row();
		row.setStyle("border:0px;background: transparent;");
		row.setParent(rows);
		row.appendChild(new Label("Dashboard 2"));
		row.appendChild(dashboard2 = new Textbox(
				tbmrole.getDashboard2() == null ? "" : tbmrole.getDashboard2()));
		dashboard2.setCols(40);

		row = new Row();
		row.setStyle("border:0px;background: transparent;");
		row.setParent(rows);
		row.appendChild(new Label("Dashboard 3"));
		row.appendChild(dashboard3 = new Textbox(
				tbmrole.getDashboard3() == null ? "" : tbmrole.getDashboard3()));
		dashboard3.setCols(40);

		row = new Row();
		row.setStyle("border:0px;background: transparent;");
		row.setParent(rows);
		South south = new South();
		south.setFlex(true);
		south.setParent(borderlayout);

		Toolbar toolbar = new Toolbar();
		toolbar.setHeight("30px");
		toolbar.setParent(south);
		Toolbarbutton cancel = new Toolbarbutton("Batal", "/img/cancel.gif");
		cancel.setTooltiptext("Tutup");
		cancel.addEventListener("onClick", new EventListener() {
			@Override
			public void onEvent(Event event) throws Exception {
				addWindow.setVisible(false);
			}
		});
		cancel.setParent(toolbar);
		Toolbarbutton save = new Toolbarbutton("Simpan", "/img/save.gif");
		save.setTooltiptext("Simpan");
		save.addEventListener("onClick", new EventListener() {
			@Override
			public void onEvent(Event event) throws Exception {
				if (onSave(event)) {
					onSearchDefault(null);
					addWindow.setVisible(false);
				}
			}
		});
		save.setParent(toolbar);
		borderlayout.setParent(addWindow);
		Caption caption = new Caption();
		Toolbarbutton button = new Toolbarbutton(" X ");
		button.addEventListener("onClick", new EventListener() {
			@Override
			public void onEvent(Event event) throws Exception {
				addWindow.setVisible(false);
			}

		});
		button.setParent(caption);
		// caption.setParent(addWindow);
	}

	public boolean onSave(Event event) throws Exception {
		if (nama.getValue().trim().equals("")) {
			Messagebox.show("Nama Tbmrole harus diisi", "Peringatan",
					Messagebox.OK, Messagebox.EXCLAMATION);
			return false;
		}

		/*
		 * if (keterangan.getValue().trim().equals("")) {
		 * Messagebox.show("Keterangan harus diisi", "Peringatan",
		 * Messagebox.OK, Messagebox.EXCLAMATION); return false; }
		 */

		boolean i = checkNamaTbmrole();
		if (i) {
			Messagebox.show("Nama Tbmrole sudah ada di database", "Peringatan",
					1, Messagebox.EXCLAMATION);
			return false;
		}

		TbmroleDao tbmroleDao = DaoFactory.getInstance().getTbmroleDao();
		if (tbmrole.getRoleId() != null) {
			tbmrole = tbmroleDao.load(tbmrole.getRoleId());

		}

		tbmrole.setDashboard(dashboard.getValue().trim());
		tbmrole.setDashboard2(dashboard2.getValue().trim());
		tbmrole.setDashboard3(dashboard3.getValue().trim());
		tbmrole.setRoleName(nama.getValue());
		tbmrole.setRoleId(kode.getValue());

		// tbmroleDao.beginTransaction();
		if (tbmrole.getRoleId() != null) {
			tbmroleDao.update(tbmrole);
		} else {
			tbmroleDao.save(tbmrole);
		}
		// tbmroleDao.commitTransaction();
		return true;
	}

	@SuppressWarnings("unchecked")
	public void onSearchDefault(Event event) {

		Session session = HibernateUtil.currentSession();
		List<Tbmrole> job = session
				.createCriteria(Tbmrole.class)
				.addOrder(Order.asc("roleName"))
				.add(Restrictions.ilike("roleName", (searchnama == null ? ""
						: searchnama.getValue()), MatchMode.ANYWHERE))
				.setMaxResults(sipus.common.Common.MAX_RESULT).list();

		ListModel strset = new SimpleListModel(job);

		grid.setRowRenderer(new TbmroleRenderer());
		grid.setModel(strset);
		grid.renderAll();
		// grid.setOddRowSclass("non-odd");

	}

	public Boolean checkNamaTbmrole() {

		Integer kotaCount = null;
		Session session = HibernateUtil.currentSession();
		kotaCount = ((Number) session
				.createCriteria(Tbmrole.class)
				.setProjection(Projections.count("roleId"))
				.add(Restrictions.eq("roleName", nama.getValue().trim()))
				.add(this.tbmrole.getRoleId() == null ? Restrictions
						.sqlRestriction("1=1") : Restrictions.ne("roleId",
						this.tbmrole.getRoleId())).uniqueResult()).intValue();

		return !kotaCount.equals(0);
	}

}
